package com.jackrain.nea.ext.oss;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 可枚举对象
 * @author blqw
 * @date 2017-12
 */
public class OssObjectEnumerable implements Iterable<OssObject> {

    private final OssObjectLoader loader;

    public OssObjectEnumerable(OssObjectLoader loader) {
        this.loader = loader;
    }

    @Override
    public Iterator<OssObject> iterator() {
        return new InnerEnumerator(loader);
    }

    /**
     * 对象枚举器
     */
    static class InnerEnumerator implements Iterator<OssObject> {

        private final OssObjectLoader loader;
        private final List<OssObject> objects;
        private int index;

        public InnerEnumerator(OssObjectLoader loader) {
            if (loader == null) {
                loader = new OssObjectLoader() {
                    @Override
                    public void load(List<OssObject> objects) {

                    }

                    @Override
                    public boolean isMore() {
                        return false;
                    }
                };
            }
            this.loader = loader;
            objects = new ArrayList<>();
            index = 0;
            loader.load(objects);
        }

        @Override
        public boolean hasNext() {
            return index < objects.size() || loader.isMore();
        }

        @Override
        public OssObject next() {
            if (index >= objects.size()) {
                if (!loader.isMore()) {
                    return null;
                }
                loader.load(objects);
                if (objects.size() == 0) {
                    return null;
                }
            }
            OssObject obj = objects.get(index);
            index++;
            if (index >= objects.size() && index > 0) {
                objects.clear();
                index = 0;
            }
            return obj;
        }
    }
}
